package core.utils;

import java.nio.ByteBuffer;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

import org.apache.commons.csv.CSVFormat;

import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.xml.DomDriver;

public final class Converter {
	private static final XStream xstream = new XStream(new DomDriver());

	private static final String dateFormatPattern = "MM.dd.yyyy HH:mm:ss";
	private static final DateFormat dateFormat = new SimpleDateFormat(dateFormatPattern);

	private static final CSVFormat csvFormat = CSVFormat.RFC4180.withDelimiter(';');

	private Converter() {

	}

	public static String getDateFormatPattern() {
		return dateFormatPattern;
	}

	public static CSVFormat getCSVFormat() {
		return csvFormat;
	}

	public static String objectToXML(Object obj) {
		if (obj == null) {
			return "";
		}
		return xstream.toXML(obj);
	}

	public static Object xmlToObject(String xml) {
		if (xml == null) {
			return null;
		}
		return xstream.fromXML(xml);
	}

	public static synchronized String dateToString(Date date) {
		if (date == null) {
			return "";
		}
		return dateFormat.format(date);
	}

	public static synchronized Date stringToDate(String strDate) {
		if (strDate == null) {
			return null;
		}
		try {
			return dateFormat.parse(strDate);
		} catch (ParseException e) {
			return null;
		}
	}

	public static synchronized byte[] uuidToByteArray(UUID uuid) {
		ByteBuffer byteBuffer = ByteBuffer.wrap(new byte[Long.SIZE * 2 / 8]);
		byteBuffer.putLong(uuid.getMostSignificantBits());
		byteBuffer.putLong(uuid.getLeastSignificantBits());

		return byteBuffer.array();
	}

	public static synchronized UUID byteArrayToUuid(byte[] byteArray) {
		ByteBuffer byteBuffer = ByteBuffer.wrap(new byte[Long.SIZE * 2 / 8]);
		byteBuffer.put(byteArray);
		byteBuffer.flip();
		long mostSignificantBits = byteBuffer.getLong();
		long leastSignificantBits = byteBuffer.getLong();

		return new UUID(mostSignificantBits, leastSignificantBits);
	}
}
